﻿//https://leetcode.cn/problems/rotate-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k)
    {
        if (k == 0 || head == nullptr || head->next == nullptr)
        {
            return head;
        }

        //找到链表的尾并统计链表长度
        ListNode* cur = head;
        int n = 1;
        while (cur->next)
        {
            cur = cur->next;
            n++;
        }

        //获取截断部位
        int x = n - k % n;
        if (x == n)
        {
            return head;
        }

        //连接首尾，使链表成环
        cur->next = head;

        while (x--)
        {
            cur = cur->next;
        }

        //断开链表
        ListNode* ret = cur->next;
        cur->next = nullptr;
        return ret;
    }
};
